package com.xiaoyu.lanling.net

import `in`.srain.cube.concurrent.SimpleTask
import `in`.srain.cube.request.CustomNetworkException
import `in`.srain.cube.util.CLog
import `in`.srain.cube.util.UTUtil
import `in`.srain.cube.util.log.LogEvent
import com.tencent.bugly.crashreport.CrashReport
import com.xiaoyu.base.net.NetworkErrorProcessor.NEED_LOGIN
import com.xiaoyu.lanling.app.AppHelper
import com.xiaoyu.lanling.common.Constant.From.GREET
import com.xiaoyu.lanling.feature.coin.activity.CoinRechargeDialogFragment
import com.xiaoyu.lanling.feature.coin.activity.CoinRechargeWithFirstChargeDialogFragment
import com.xiaoyu.lanling.log.AppLogClient
import com.xiaoyu.lanling.router.Router

class CustomNetworkErrorProcessor {

    companion object {
        private val TAG: String = CustomNetworkErrorProcessor::class.java.simpleName

        private const val SYSTEM_BLACKED = 100010;

        private const val COIN_NOT_ENOUGH = 700002;
        private const val COIN_NOT_ENOUGH_WITH_FIRST_CHARGE = 700009;

        fun process(exception: CustomNetworkException) {
            when (exception.code) {
                NEED_LOGIN -> {
                    CLog.e(TAG, "request fail: need login")
                    AppHelper.afterLogout(Runnable { Router.instance.gotoLoginActivity() })

                    val logEvent = LogEvent("logout")
                    logEvent.putData("reason", "needLogin")
                    AppLogClient.instance.addLog(logEvent)
                }
                SYSTEM_BLACKED -> {
                }
                COIN_NOT_ENOUGH -> showCoinRechargeDialog()
                COIN_NOT_ENOUGH_WITH_FIRST_CHARGE -> showCoinChargeWithFirstCharge()
            }
            CrashReport.postCatchedException(exception)
        }

        private fun showCoinRechargeDialog() {
            SimpleTask.post {
                CoinRechargeDialogFragment.show(GREET)
            }
        }

        private fun showCoinChargeWithFirstCharge() {
            SimpleTask.post {
                CoinRechargeWithFirstChargeDialogFragment.show()
            }
        }
    }
}